package com.healthyeating.manage.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.healthyeating.common.exception.ServiceException;
import com.healthyeating.common.utils.DateUtils;
import com.healthyeating.common.utils.SecurityUtils;
import com.healthyeating.manage.domain.ActivityUser;
import com.healthyeating.manage.domain.Message;
import com.healthyeating.manage.domain.TakePart;
import com.healthyeating.manage.domain.vo.ActivityUserVo;
import com.healthyeating.manage.mapper.ActivityUserMapper;
import com.healthyeating.manage.mapper.MessageMapper;
import com.healthyeating.manage.mapper.TakePartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.healthyeating.manage.mapper.ActivityMapper;
import com.healthyeating.manage.domain.Activity;
import com.healthyeating.manage.service.IActivityService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 活动Service业务层处理
 *
 * @author 段奇乐
 * @date 2025-04-12
 */
@Service
public class ActivityServiceImpl implements IActivityService {

    @Autowired
    private TakePartMapper takePartMapper;

    @Autowired
    private ActivityUserMapper activityUserMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private MessageMapper messageMapper;


    /**
     * 查询活动
     *
     * @param activityId 活动主键
     * @return 活动
     */
    @Override
    public Activity selectActivityByActivityId(Long activityId) {
        return activityMapper.selectActivityByActivityId(activityId);
    }

    /**
     * 查询活动列表
     *
     * @param activity 活动
     * @return 活动
     */
    @Override
    public List<Activity> selectActivityList(Activity activity) {
        return activityMapper.selectActivityList(activity);
    }

    /**
     * 新增活动
     *
     * @param activity 活动
     * @return 结果
     */
    @Override
    public int insertActivity(Activity activity) {
        activity.setParticipantsNum(0);
        activity.setCreateTime(DateUtils.getNowDate());
        return activityMapper.insertActivity(activity);
    }

    /**
     * 修改活动
     *
     * @param activity 活动
     * @return 结果
     */
    @Override
    public int updateActivity(Activity activity) {
        return activityMapper.updateActivity(activity);
    }

    /**
     * 批量删除活动
     *
     * @param activityIds 需要删除的活动主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteActivityByActivityIds(Long[] activityIds) {
//        int result = activityMapper.deleteActivityByActivityIds(activityIds);
        // 删除参与的人的记录
        for (Long activityId : activityIds) {
            ActivityUser activityUser = new ActivityUser();
            activityUser.setActivityId(activityId);
            List<ActivityUser> activityUserList = activityUserMapper.selectActivityUserList(activityUser);
            activityUserList.forEach(_activityUser -> {
                Message message = new Message();
                message.setAssociationId(activityId);
                message.setSource("tb_activity");
                message.setUserId(_activityUser.getUserId());
                message.setIsRead("N");
                message.setIsShow("Y");
                messageMapper.insertMessage(message);
            });
            activityUserMapper.deleteActivityUserByActivityId(activityId);
        }
        return activityMapper.removeActivityByActivityIds(activityIds);
    }

    /**
     * 删除活动信息
     *
     * @param activityId 活动主键
     * @return 结果
     */
    @Override
    public int deleteActivityByActivityId(Long activityId) {
        return activityMapper.deleteActivityByActivityId(activityId);
    }


    /**
     * 查询用户参与活动记录
     *
     * @param activityUser 活动参与记录
     * @return 用户参与记录集合
     */
    @Override
    public Map<String, Object> selectActivityUserList(ActivityUser activityUser) {
        Map<String, Object> map = new HashMap<>();
        activityUser.setUserId(SecurityUtils.getUserId());
        List<ActivityUser> activityUserList = activityUserMapper.selectActivityUserList(activityUser);
        List<ActivityUserVo> activityUserVoList = activityUserList.stream().map(_activityUser -> {
            ActivityUserVo activityUserVo = new ActivityUserVo();
            BeanUtil.copyProperties(_activityUser, activityUserVo);
            activityUserVo.setActivity(activityMapper.selectActivityByActivityId(_activityUser.getActivityId()));
            TakePart takePart = new TakePart();
            takePart.setActivityUserId(_activityUser.getActivityUserId());
            takePart.setUserId(SecurityUtils.getUserId());
            Map<String, Object> _map = DateUtils.extractTime(DateUtils.getNowDate());
            takePart.setStartOfDay((Date) _map.get("startOfDay"));
            takePart.setEndOfDay((Date) _map.get("endOfDay"));
            List<TakePart> takePartList = takePartMapper.selectTakePartList(takePart);
            if (takePartList != null && !takePartList.isEmpty()) {
                activityUserVo.setClockStatus(1);
            } else {
                activityUserVo.setClockStatus(0);
            }
            return activityUserVo;
        }).collect(Collectors.toList());
        map.put("oldList", activityUserList);
        map.put("newList", activityUserVoList);
        return map;
    }

    /**
     * 参与活动
     *
     * @param activityUser 活动参与记录
     * @return 结果
     */
    @Override
    @Transactional
    public int insertActivityUser(ActivityUser activityUser) {
        activityUser.setCreateTime(DateUtils.getNowDate());
        activityUser.setUserId(SecurityUtils.getUserId());
        if (activityUser.getActivityId() != null) {
            Activity activity = activityMapper.selectActivityByActivityId(activityUser.getActivityId());
            if (activity.getParticipantsNum() < activity.getMaxParticipantsNum()) {
                activity.setParticipantsNum(activity.getParticipantsNum() + 1);
                activityMapper.updateActivity(activity);
            } else {
                throw new ServiceException("活动人数已满");
            }
        }
        return activityUserMapper.insertActivityUser(activityUser);
    }

    /**
     * 打卡
     *
     * @param takePart 打卡信息
     * @return 结果
     */
    @Override
    public int clockIn(TakePart takePart) {
        takePart.setUserId(SecurityUtils.getUserId());
        takePart.setCreateTime(DateUtils.getNowDate());
        return takePartMapper.insertTakePart(takePart);
    }

    /**
     * 批量退出参加活动
     *
     * @param activityUserIds 需要退出的活动主键集合
     * @return 结果
     */
    @Override
    public int deleteActivityUserByActivityUserIds(Long[] activityUserIds) {
        return activityUserMapper.deleteActivityUserByActivityUserIds(activityUserIds);
    }
}
